package modelo.hibernate.dao;

import modelo.entidad.*;

import java.util.ArrayList;
import java.util.List;

import modelo.hibernate.config.Sesion;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

public class DaoPublicacion {

	private Sesion sesionPostgres;
	
	public void agregarPublicacion(Publicacion dato) throws Exception{
		@SuppressWarnings("static-access")
		Session em = sesionPostgres.openSession();  
         Transaction tx = null;  
         try {    
        	 tx = em.beginTransaction();
              em.save( dato);   
              tx.commit();  
         } catch (Exception e) {  
             tx.rollback();            
             e.printStackTrace();
             throw e;
         } finally {  
             em.close();  
         } 
	}
	
	public void actualizarPublicacion(Publicacion dato) throws Exception{
		@SuppressWarnings("static-access")
		Session em = sesionPostgres.openSession();  
         Transaction tx = null;  
         try {    
        	 tx = em.beginTransaction();
              em.update(dato);   
              tx.commit();  
         } catch (Exception e) {  
             tx.rollback();            
             e.printStackTrace();
             throw e;
         } finally {  
             em.close();  
         } 
	}
	
	public Publicacion obtenerPublicacion(int id) throws Exception{		 
	    @SuppressWarnings("static-access")
		Session sesion = sesionPostgres.openSession();  
            Publicacion dato = null;        
            try{
            	dato = (Publicacion) sesion.get(Publicacion.class,  id);
            } catch (Exception e) {  
            e.printStackTrace();
           
            throw new Exception(e.getMessage(),e.getCause());
            }  finally {  
                sesion.close();  
            }  
           
	    return dato;
}
	public Publicacion findPublicacionporPlaca(int id) throws Exception{
		Publicacion dato = new Publicacion();
		Session em = sesionPostgres.openSession();
		try
		{
			dato = (Publicacion)em.createQuery("SELECT p FROM Publicacion p WHERE id= '"+id+"'").uniqueResult();
			
		}catch (Exception e) {             
		       
	         throw new Exception(e.getMessage(),e.getCause());
	        } finally {  
	          em.close();  
	        }
		return dato;
	}
	public List<Publicacion> obtenerTodos() throws Exception { 
		List<Publicacion> datos = new ArrayList<Publicacion>(); 
		Session em = sesionPostgres.openSession(); 
		try { 
			datos = (List<Publicacion>) em.createCriteria(Publicacion.class).list();
			} catch (Exception e) { 
				throw new Exception(e.getMessage(),e.getCause());
			   } finally { 
				   em.close();
				   } 
		return datos;
		}
	
}
